package steak.xteamy.client.VoiceChat;

import net.fabricmc.fabric.api.client.networking.v1.ClientPlayNetworking;
import net.minecraft.client.MinecraftClient;
import net.minecraft.client.gui.DrawContext;
import net.minecraft.client.gui.navigation.GuiNavigation;
import net.minecraft.client.gui.navigation.GuiNavigationPath;
import net.minecraft.client.gui.screen.narration.NarrationMessageBuilder;
import net.minecraft.client.gui.tooltip.Tooltip;
import net.minecraft.client.gui.widget.PressableWidget;
import net.minecraft.client.util.math.MatrixStack;
import net.minecraft.item.ItemStack;
import net.minecraft.item.Items;
import net.minecraft.text.Text;
import net.minecraft.util.Colors;
import net.minecraft.util.math.ColorHelper;
import org.joml.Vector2i;
import steak.xteamy.Network.Packets;
import steak.xteamy.client.ChannelButtonState;
import steak.xteamy.client.KillerGroupClient;

import java.util.List;

public class ChatScreenComponent {
    private final ChannelButtonState channelButtonState = KillerGroupClient.channelButtonState;

    private final List<ChannelButton> channelButtons = List.of(
            new ChannelButton(Text.of("公共"), new ItemStack(Items.AXOLOTL_BUCKET), 0),
            new ChannelButton(Text.of("狼人"), new ItemStack(Items.OMINOUS_BOTTLE), 1),
            new ChannelButton(Text.of("死亡"), new ItemStack(Items.SKELETON_SKULL), 2)
    );

    private static final MinecraftClient client = MinecraftClient.getInstance();

    public ChatScreenComponent() {
        Text keyText = KillerGroupClient.KEY_WOLF_CHANNEL.getBoundKeyLocalizedText();

        Text PUBLIC_CHANNEL = Text.literal("§l公共语音频道").withColor(Colors.WHITE)
                .append("\n").append(Text.literal("•有效范围：20格半径范围内").withColor(Colors.LIGHT_GRAY))
                .append("\n").append(Text.literal("•发言规则：自由发言，默认开启").withColor(Colors.LIGHT_GRAY));

        Text WOLF_CHANNEL = Text.literal("§l狼人语音频道").withColor(Colors.LIGHT_RED)
                .append("\n").append(Text.literal("•有效范围：无限").withColor(Colors.LIGHT_GRAY))
                .append("\n").append(Text.literal("•双通道监听：").withColor(Colors.LIGHT_GRAY))
                .append("\n").append(Text.literal(" ▸可听到公共频道语音").withColor(Colors.LIGHT_GRAY))
                .append("\n").append(Text.literal(" ▸其他玩家无法收听此频道语音").withColor(Colors.LIGHT_GRAY))
                .append("\n").append(Text.literal("•切换方式：手动切换或").withColor(Colors.LIGHT_GRAY)
                        .append(Text.literal("[").append(keyText).append("]").withColor(Colors.YELLOW)));

        Text DEATH_CHANNEL = Text.literal("§l死亡语音频道").withColor(Colors.GRAY)
                .append("\n").append(Text.literal("•激活条件：玩家死亡后自动接入").withColor(Colors.LIGHT_GRAY))
                .append("\n").append(Text.literal("•权限限制：").withColor(Colors.LIGHT_GRAY))
                .append("\n").append(Text.literal(" ▸禁止切换频道").withColor(Colors.LIGHT_GRAY))
                .append("\n").append(Text.literal(" ▸可收听全部频道语音").withColor(Colors.LIGHT_GRAY))
                .append("\n").append(Text.literal(" ▸仅限死亡玩家间交流").withColor(Colors.LIGHT_GRAY));

        channelButtons.get(0).setSelFocused(channelButtonState.getBoolean(0));
        channelButtons.get(1).setSelFocused(channelButtonState.getBoolean(1));
        channelButtons.get(2).setSelFocused(channelButtonState.getBoolean(2));

        channelButtons.get(0).setTooltip(Tooltip.of(PUBLIC_CHANNEL));
        channelButtons.get(1).setTooltip(Tooltip.of(WOLF_CHANNEL));
        channelButtons.get(2).setTooltip(Tooltip.of(DEATH_CHANNEL));

        for (ChannelButton button : channelButtons) {
            button.visible = false;
        }
        channelButtons.get(0).visible = (KillerGroupClient.channelP != -1);
        channelButtons.get(1).visible = channelButtonState.getBoolean(1);
        channelButtons.get(2).visible = channelButtonState.getBoolean(2);
    }

    public List<ChannelButton> getChannelButtons() {
        return channelButtons;
    }

    public void render(DrawContext context, int mouseX, int mouseY, float delta) {

        int marginX = 0;
        for (ChannelButton channelButton : channelButtons) {
            channelButton.setFocused(false);
            if (!channelButton.visible) {
                continue;
            }
            if (!channelButton.isHovered()) {
                context.setShaderColor(1.0f, 1.0f, 1.0f, 0.65f);
            }
            channelButton.setOffsetX(marginX);
            channelButton.render(context, mouseX, mouseY, delta);
            context.setShaderColor(1.0f, 1.0f, 1.0f, 1.0f);

            marginX += channelButton.getSize().x + 4;
        }

        this.buttonUpdate();
        this.setVisible();
    }

    private void setVisible() {
        int k = KillerGroupClient.channelP;
        channelButtons.get(0).visible = (k != -1);
        channelButtons.get(1).visible = false;
        channelButtons.get(2).visible = false;

        if (k == 1)  {
            channelButtons.get(1).visible = true;
        } else if (k == 2)  {
            channelButtons.get(2).visible = true;
        }
    }

    public void resize() {
        for (ChannelButton channelButton : channelButtons) {
            channelButton.resize();
        }
    }

    private void buttonUpdate() {
        ChannelButton updateButton = null;
        for (ChannelButton channelButton : channelButtons) {
            if (channelButton.selFocusedUpdate) {
                updateButton = channelButton;
                break;
            }
        }

        if (updateButton != null) {
            for (ChannelButton channelButton2 : channelButtons) {
                channelButton2.setSelFocused(false);
            }
            if (KillerGroupClient.channelP == 2) {
                channelButtons.get(2).setSelFocused(true);
                channelButtonState.reset();
                channelButtonState.setBoolean(2, true);
            } else {
                if (KillerGroupClient.channelP == 1 && !KillerGroupClient.channelButtonState.getBoolean(updateButton.getIndex())) {
                    ClientPlayNetworking.send(new Packets.Channel(updateButton.getIndex()));
                }

                updateButton.setSelFocused(true);
                channelButtonState.reset();
                channelButtonState.setBoolean(updateButton.getIndex(), true);

            }
            updateButton.selFocusedUpdate = false;
        }
    }

    public static class ChannelButton extends PressableWidget {

        private final ItemStack itemStack;

        private Vector2i size = new Vector2i();
        private boolean selFocused = false;
        public boolean selFocusedUpdate = false;
        private final int index;

        public ChannelButton(Text text, ItemStack itemStack, int index) {
            super(2, client.getWindow().getScaledHeight() - 28, 12 + 4 + client.textRenderer.getWidth(text), 12, text);
            this.itemStack = itemStack;
            this.index = index;
        }

        @Override
        public void onPress() {
        }

        @Override
        public GuiNavigationPath getNavigationPath(GuiNavigation navigation) {
            return null;
        }

        @Override
        public boolean keyPressed(int keyCode, int scanCode, int modifiers) {
            return false;
        }

        @Override
        protected void renderWidget(DrawContext context, int mouseX, int mouseY, float delta) {
            int x1 = this.getX();
            int y1 = this.getY();
            int x2 = x1 + this.getWidth();
            int y2 = y1 + this.getHeight();

            context.fill(x1, y1, x2, y2, ColorHelper.Argb.getArgb((int) ((0.65f + (this.isSelFocused() ? 0.35f : 0.0f)) * 255), 0, 0, 0));
            MatrixStack matrixStack = context.getMatrices();
            matrixStack.push();
            float k = 10.0f / 16.0f;
            float m = 1.0f - k;
            matrixStack.translate(x1 * m, y1 * m, 0.0f);
            matrixStack.scale(k, k, k);
            context.drawItem(itemStack, x1 + 3, y1 + 1);
            matrixStack.pop();
            context.drawText(client.textRenderer, this.getMessage(), x1 + 3 + 12, y1 + 2, -1, true);
            if (this.isSelFocused()) {
                context.fill(x1, y2 - 1, x2, y2, ColorHelper.Argb.getArgb(210, 255, 255, 255));
            }
            this.size = new Vector2i(x2 - x1, 12);
        }

        @Override
        public void onClick(double mouseX, double mouseY) {
            selFocusedUpdate = true;
        }

        @Override
        public boolean isFocused() {
            return false;
        }

        @Override
        protected void appendClickableNarrations(NarrationMessageBuilder builder) {

        }

        public void setOffsetX(int offsetX) {
            super.setX(2 + offsetX);
        }

        public Vector2i getSize() {
            return this.size;
        }

        public boolean isSelFocused() {
            return selFocused;
        }

        public void setSelFocused(boolean selFocused) {
            this.selFocused = selFocused;
        }

        public void resize() {
            super.setY(client.getWindow().getScaledHeight() - 28);
        }

        public int getIndex() {
            return index;
        }
    }
}
